import { api } from '@/utils/request'

const state = {
  familyInfo: null,
  familyMembers: [],
  inviteCode: ''
}

const mutations = {
  SET_FAMILY_INFO(state, info) {
    state.familyInfo = info
  },
  
  SET_FAMILY_MEMBERS(state, members) {
    state.familyMembers = members
  },
  
  SET_INVITE_CODE(state, code) {
    state.inviteCode = code
  },
  
  REMOVE_MEMBER(state, memberId) {
    state.familyMembers = state.familyMembers.filter(member => member.id !== memberId)
  },
  
  UPDATE_MEMBER(state, updatedMember) {
    const index = state.familyMembers.findIndex(member => member.id === updatedMember.id)
    if (index !== -1) {
      state.familyMembers.splice(index, 1, updatedMember)
    }
  }
}

const actions = {
  // 创建家庭
  async createFamily({ commit }, familyData) {
    try {
      const response = await api.post('/family/create', familyData)
      
      const family = response.data
      commit('SET_FAMILY_INFO', family)
      commit('SET_INVITE_CODE', family.inviteCode)
      
      // 更新用户信息中的familyId
      const userInfo = uni.getStorageSync('userInfo')
      userInfo.familyId = family.id
      uni.setStorageSync('userInfo', userInfo)
      commit('user/SET_USER_INFO', userInfo, { root: true })
      
      return family
    } catch (error) {
      console.error('创建家庭失败:', error)
      throw error
    }
  },
  
  // 加入家庭
  async joinFamily({ commit }, inviteCode) {
    try {
      const response = await api.post('/family/join', { inviteCode: inviteCode })
      
      const family = response.data
      commit('SET_FAMILY_INFO', family)
      
      // 更新用户信息中的familyId
      const userInfo = uni.getStorageSync('userInfo')
      userInfo.familyId = family.id
      uni.setStorageSync('userInfo', userInfo)
      commit('user/SET_USER_INFO', userInfo, { root: true })
      
      return family
    } catch (error) {
      console.error('加入家庭失败:', error)
      throw error
    }
  },
  
  // 获取家庭统计信息
  async getFamilyStats({ commit }) {
    try {
      const response = await api.get('/family/stats')
      
      return response.data
    } catch (error) {
      console.error('获取家庭统计信息失败:', error)
      throw error
    }
  },
  
  // 获取家庭信息
  async getFamilyInfo({ commit }) {
    try {
      const response = await api.get('/family/info')
      
      commit('SET_FAMILY_INFO', response.data)
      return response.data
    } catch (error) {
      console.error('获取家庭信息失败:', error)
      throw error
    }
  },
  
  // 更新家庭信息
  async updateFamilyInfo({ commit }, familyData) {
    try {
      const response = await api.put('/family/update', familyData)
      
      commit('SET_FAMILY_INFO', response.data)
      return response.data
    } catch (error) {
      console.error('更新家庭信息失败:', error)
      throw error
    }
  },
  
  // 获取家庭成员列表
  async getFamilyMembers({ commit }) {
    try {
      const response = await api.get('/family/members')
      
      const members = response.data || []
      commit('SET_FAMILY_MEMBERS', members)
      return members
    } catch (error) {
      console.error('获取家庭成员失败:', error)
      throw error
    }
  },
  
  async removeMember({ commit }, memberId) {
    try {
      await api.delete(`/family/members/${memberId}`)
      commit('REMOVE_MEMBER', memberId)
    } catch (error) {
      console.error('移除家庭成员失败:', error)
      throw error
    }
  },
  
  async updateMember({ commit }, { memberId, memberData }) {
    try {
      const response = await api.put(`/family/members/${memberId}`, memberData)
      commit('UPDATE_MEMBER', response.data)
      return response.data
    } catch (error) {
      console.error('更新成员关系失败:', error)
      throw error
    }
  },
  
  // 生成新的邀请码
  async generateInviteCode({ commit }) {
    try {
      const response = await api.post('/family/refresh-invite-code')
      
      const inviteCode = response.data.inviteCode
      commit('SET_INVITE_CODE', inviteCode)
      
      // 同时更新 familyInfo 中的邀请码
      const familyInfo = this.state.familyInfo
      if (familyInfo) {
        familyInfo.inviteCode = inviteCode
        commit('SET_FAMILY_INFO', familyInfo)
      }
      
      return inviteCode
    } catch (error) {
      console.error('生成邀请码失败:', error)
      throw error
    }
  },
  
  // 退出家庭
  async leaveFamily({ commit }) {
    try {
      await api.post('/family/leave')
      
      // 清除家庭相关数据
      commit('SET_FAMILY_INFO', null)
      commit('SET_FAMILY_MEMBERS', [])
      commit('SET_INVITE_CODE', '')
      
      // 更新用户信息
      const userInfo = uni.getStorageSync('userInfo')
      userInfo.family_id = null
      uni.setStorageSync('userInfo', userInfo)
      commit('user/SET_USER_INFO', userInfo, { root: true })
      
    } catch (error) {
      console.error('退出家庭失败', error)
      throw error
    }
  },
  
  // 更新隐私设置
  async updatePrivacySettings({ commit, state }, privacySettings) {
    try {
      const response = await api.post('/family/privacy-settings', privacySettings)
      
      // 更新本地家庭信息
      const familyInfo = { ...state.familyInfo }
      familyInfo.isPublic = privacySettings.isPublic
      familyInfo.allowSearch = privacySettings.allowSearch
      familyInfo.requireApproval = privacySettings.requireApproval
      commit('SET_FAMILY_INFO', familyInfo)
      
      return response
    } catch (error) {
      console.error('更新隐私设置失败:', error)
      throw error
    }
  },

}

const getters = {
  familyInfo: state => state.familyInfo,
  familyMembers: state => state.familyMembers,
  inviteCode: state => state.inviteCode,
  familyId: state => state.familyInfo?.id,
  familyName: state => state.familyInfo?.name,
  memberCount: state => state.familyMembers.length,
  isCreator: (state, getters, rootState) => {
    return state.familyInfo?.creatorId === rootState.user.userInfo?.id
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 
